package com.threadStudy;

import java.util.concurrent.TimeUnit;

/**
 * Created by shaxj on 16/6/16.
 */
public class WaitNotify {
    static boolean flag = true;
    static Object lock = new Object();

    public static void main(String args[]) throws Exception {

        Thread waitThread = new Thread(new Wait(), "waitThread");
        waitThread.start();
        TimeUnit.SECONDS.sleep(1);
        Thread notifyThread = new Thread(new Notify(), "notifyThread");
        notifyThread.start();

        final int test =1;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
               int x=  test;
            }
        });
        thread.start();
    }

    static class Wait implements Runnable {

        @Override
        public void run() {

            synchronized (lock) {

                while (flag) {

                    try {
                        System.out.println(Thread.currentThread() + "flag is true.wait@");

                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(Thread.currentThread() + "flag is false. running @");

            }
        }
    }

    static class Notify implements Runnable {
        @Override
        public void run() {

            synchronized (lock) {
                try {
                    System.out.println(Thread.currentThread() + "hold lock.notify @");

                    lock.notifyAll();
                    TimeUnit.SECONDS.sleep(10);
                    flag = false;

                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " hold lock again . sleep @");

            }
        }
    }

}
